// __inline('load.js');
nie.define("Index",function(){
    var _common=nie.require("Common");
    var isAppInside=/micromessenger/i.test(navigator.userAgent.toLowerCase());
    var isIos= /iphone os/i.test(navigator.userAgent.toLowerCase())||/ipad/i.test(navigator.userAgent.toLowerCase());
    var isAndroid = /android/i.test(navigator.userAgent.toLowerCase());

    //根据接口返回数字，对应服务器名称
    var serverDefault ={
        '10013':'桂之馥',
        '15027':'风雨同行',
        '10000':'两情相悦',
        '15030':'春樱共赏',
        '15029':'两情相悦',
        '15032':'谜之暗影',
    };

    //用于60s 手机号获取间隔
    var t,t2; 

    //记录抽卡剩余次数
    var manyCard; 
    //记录最后保存的式神
    var lastSaveNum;

    //requestAni canvas注册 保存变量
    var start = null;
    var start2 = null;
    var stepFn,stepFn2;

    //抽奖结果对应式神列表
    var ssData = __inline('ssData.js');

    //接口host
    var hosturl = '//g37-capsule-toys.webapp.163.com/';
    var hosturl2 = '//com-sev.webapp.163.com/g37/query_apntnum';

    //拖动时纸人保存变量
    var down=null;

    //是否第一次拖动纸人
    var isFirstMove = true;
    var canCall = true; //标识是否可以召唤式神
    var cTimer = null; //计时器变量

    //记录纸人位置
    var zhirenXY = {
        X : 0,
        Y : 0
    }

    var canvasD; //召唤阵帧动画
    var canvasD2; //爆炸帧动画
    var frameCache; //爆炸帧动画 中间变量 用于重置动画顺序
    var mySwiper; //全局swiper变量
    var isfirstsave = false; //标识是否第一次抽取的变量

    //预加载图片数组
    var img_list1 = __resload('img');
    var img_list2 = __resload('data/zhz_ani');
    var img_list3 = __resload('data/bz');
    var img_list = img_list1.concat(img_list2).concat(img_list3);

    //帧动画空数组
    var firesImg = [];
    var bzImg = [];

    //帧动画图片排序
	function sortFunc(a,b){
		var int = function(n){
			return parseInt(n.split('/').pop().replace(/[^0-9]/ig,""))
		}
		return int(a) - int(b);
	}



    //保存图片到帧动画数组
    function cachefiresImg(){
	    img_list2.sort(sortFunc)
	    for(var i=0;i<img_list2.length;i++){
            firesImg[i] = new Image();
            firesImg[i].src = img_list2[i];
        }
	    img_list3.sort(sortFunc);
	    for(var j=0;j<img_list3.length;j++){
            bzImg[j] = new Image();
            bzImg[j].src = img_list3[j];
        }
    }

    //召唤阵帧动画
    function setCanAni(){
        var img = null;
        var frame = 1;
        var lastUpdateTime = 0;
        var acDelta = 0;
        var msPerFrame = 60;
        var w = parseFloat($('.p2-zhz-2').css('width'));
        var h = parseFloat($('.p2-zhz-2').css('height'));
        $('.p2-zhz-2 canvas').attr('width',w);
        $('.p2-zhz-2 canvas').attr('height',h);
        //第一步：获取canvas元素
        var canvasDom = document.getElementById("p2-zhz-2");
        //第二步：获取上下文
        var ctx = canvasDom.getContext('2d');

        function redraw() {
            ctx.clearRect(0,0,w,h);
            ctx.globalAlpha=1;
            ctx.fillStyle="transparent";
            ctx.fillRect(0, 0, w,h);
            ctx.drawImage(firesImg[frame], 0, 0, w,h);
        }
        var step = function() {
            start = requestAnimationFrame(step);
            var delta = Date.now() - lastUpdateTime;
            //console.log(Date.now(),lastUpdateTime);
            if (acDelta > msPerFrame)
            {
                acDelta = 0;
                redraw();
                // img.src= firesImg[frame];
                frame++; 
                if(frame > 45) {
                    frame = 0; //当绘制后且帧推进完，计时器就会重置。
                }
            } else {

            acDelta += delta;

            }
            lastUpdateTime = Date.now();
        };
        stepFn = step;
    }

    //爆炸帧动画
    function setCanAniBz(){
        var img = null;
        frameCache = 0;
        var lastUpdateTime = 0;
        var acDelta = 0;
        var msPerFrame = 60;
        var w = parseFloat($('.p2-bz').css('width'));
        var h = parseFloat($('.p2-bz').css('height'));
        $('.p2-bz canvas').attr('width',w);
        $('.p2-bz canvas').attr('height',h);
        //第一步：获取canvas元素
        var canvasDom = document.getElementById("p2-bz");
        //第二步：获取上下文
        var ctx = canvasDom.getContext('2d');

        function redraw() {
            ctx.clearRect(0,0,w,h);
            ctx.globalAlpha=1;
            ctx.fillStyle="transparent";
            ctx.fillRect(0, 0, w,h);
            ctx.drawImage(bzImg[frameCache], 0, 0, w,h);
        }
        var step = function() {
            start2 = requestAnimationFrame(step);
            var delta = Date.now() - lastUpdateTime;
            //console.log(Date.now(),lastUpdateTime);
            if (acDelta > msPerFrame)
            {
                acDelta = 0;
                redraw();
                // img.src= firesImg[frame];
                frameCache++; 
                if(frameCache > 31) {
                    frameCache = 31; //当绘制后且帧推进完，计时器就会重置。
                }
            } else {

            acDelta += delta;

            }
            lastUpdateTime = Date.now();
        };
        stepFn2 = step;
    }

    //重置纸人随机动作
    function ramAni(){
        $('.p2-zr,.p2-zr-on').removeClass('ram1').removeClass('ram2').removeClass('ram3').removeClass('ram4');
        var ram = Math.ceil(Math.random()*4);
        ramClass = 'ram' + ram;
        $('.p2-zr,.p2-zr-on').addClass(ramClass);
    }

    //重置纸人随机位置
    function ramPlace(){

        var halfObjW = $('.p2-zr-on').width()/2, //纸人高度一半
            halfObjH = $('.p2-zr-on').height()/2;    //纸人高度一半
        var wW = $(window).width(),
            wH = $(window).height(),
            tOffsetTop = $('.zr-target').offset().top, //召唤阵响应区域top
            tOffsetLeft = $('.zr-target').offset().left, //召唤阵响应区域left
            tgH = $('.zr-target').height(), //召唤阵响应区域高
            tgW = $('.zr-target').width(), //召唤阵响应区域宽
            tmpY = $('.zr-target').offset().top - wH/2, //中间变量高度
            tmpX = wW/2 - $('.zr-target').offset().left, //中间变量宽度
            startWL= parseFloat($('.p2-zr-start').css('width')), //初始纸人宽
            startWH=  parseFloat($('.p2-zr-start').css('height')), //初始纸人高
            ramL,ramR; //随机变量

        //如果纸人在召唤阵中，或者在屏幕下半区域，重新随机位置
        do{
            ramL = Math.ceil(Math.random()*wW);
            ramT = Math.ceil(Math.random()*wH);
            if(ramL+startWL>$(window).width()){
                ramL = $(window).width()-startWL;
                $('.p2-zr-start').css({"left":ramL});
            }
            if(ramT+startWH>$(document).height()){
                ramT = $(document).height()-startWH;
                $('.p2-zr-start').css({"top":ramT});
            }
            zhirenXY.X = ramL;
            zhirenXY.Y = ramT;
            $('.p2-zr-start').css({"left":zhirenXY.X,"top": zhirenXY.Y});
            $('.p2-zr-on').css({'top':zhirenXY.Y,'left':zhirenXY.X});

        }while((zhirenXY.Y+parseInt($('.p2-zr-on').css('height'))/2 > wH/2)||(zhirenXY.X > wW/2-tmpX && zhirenXY.X< wW/2+tmpX && zhirenXY.Y-halfObjH/2 > wH/2+tmpY && zhirenXY.Y+halfObjH/2 < wH/2+tmpY+tgH))

    };

    //召唤页面算法逻辑
    var moC = function moveCall(){
        var getC = _ajxFn();
        var isTouch = 'ontouchstart' in window
        var mouseEvents = (isTouch) ?
        {
            down: 'touchstart',
            move: 'touchmove',
            up: 'touchend',
            over: 'touchstart',
            out: 'touchend'
        }
                :
        {
            down: 'mousedown',
            move: 'mousemove',
            up: 'mouseup',
            over: 'mouseover',
            out: 'mouseout'
        }

        var originPlace = {
            x : 0,
            y : $(window).height()
        }

        

        var eventHandlers={
            touchStart:function(){
     
            }
        }

        var halfObjW = $('.p2-zr-on').width()/2,
            halfObjH = $('.p2-zr-on').height()/2;

        //鼠标按下
        function mouseD(e, opts, corner){
            down=this;
            // console.log(this);
            e.preventDefault();
            mySwiper.detachEvents();
            $('#p2-zr-on').addClass('drag');
            if(isAppInside||isIos){
                if($('.musicbtn').hasClass('active')){
                    $('#au4')[0].play();
                }
            }
            return false;
        }

        //鼠标移动
        function mouseM(e, opts, corner){
            var wW = $(window).width(), //详细注释见 ramPlace() 函数
                wH = $(window).height(),
                tOffsetTop = $('.zr-target').offset().top,
                tOffsetLeft = $('.zr-target').offset().left,
                tgH = $('.zr-target').height(),
                tgW = $('.zr-target').width(),
                tmpY = $('.zr-target').offset().top - wH/2,
                tmpX = wW/2 - $('.zr-target').offset().left;
            
            //纸人对象
            if(down){
                e.preventDefault();
                e=e.changedTouches? e.changedTouches[0]:e;
                $(down).css({"left":e.pageX-halfObjW,"top": e.pageY-halfObjH});
                
                //纸人超出屏幕时 重置位置
                if(e.pageX-halfObjW<0){
                    $(down).css({"left":"0"});
                }
                if(e.pageY-halfObjH<0){
                    $(down).css({"top":"0"});
                }
                if(e.pageX+halfObjW>$(window).width()){
                    $(down).css({"left":$(window).width()-halfObjW*2});
                }
                if(e.pageY+halfObjH>$(document).height()){
                    $(down).css({"top":$(document).height()-halfObjH*2});
                }
                // console.log(e);

                //更新纸人坐标
                zhirenXY.X = e.pageX;
                zhirenXY.Y = e.pageY;
                // if(!(zhirenXY.X > wW/2-tmpX && zhirenXY.X< wW/2+tmpX && zhirenXY.Y-halfObjH/2 > wH/2+tmpY && zhirenXY.Y+halfObjH/2 < wH/2+tmpY+tgH)){
                //     $('.p2-zhz-2').hide();
                // }else{
                //     $('.p2-zhz-2').show();
                // }
                // if(!(zhirenXY.X > wW/2-tmpX && zhirenXY.X< wW/2+tmpX && zhirenXY.Y-halfObjH/2 > wH/2+tmpY && zhirenXY.Y+halfObjH/2 < wH/2+tmpY+tgH)){
                //     $('.p2-zhz-2').removeClass('show');
                // }else{
                //     $('.p2-zhz-2').addClass('show');
                // }

                //当纸人拖动到召唤阵位置
                if(canCall && zhirenXY.X > wW/2-tmpX+0.4*tmpX && zhirenXY.X< wW/2+tmpX-0.3*tmpX && zhirenXY.Y-halfObjH/2 > wH/2+tmpY && zhirenXY.Y+halfObjH/2 < wH/2+tmpY-0.3*tmpY+tgH){
                    canCall = false;
                    mySwiper.attachEvents();
                    // mySwiper.slideTo(2);
                    // console.log(wW,wH,e);
                    $(down).css({"top":tgH/2-halfObjH+tOffsetTop,"left":tgW/2-halfObjW+tOffsetLeft});
                    if(isAppInside||isIos){
                        if($('.musicbtn').hasClass('active')){
                            $('#au5')[0].play();
                        }
                    }
                    $('.call-btn').addClass('show');
                    $('.p2-zhz-3').addClass('show');
                    $('.p2-zhz-2').addClass('show');
                    $('.p2-zr-on').hide();
                    $('.p2-zhz-zr').show();
                    $('.p2-zhz').css('visibility','hidden');
                    var tim = setTimeout(function(){
                        $('.p2-bz').addClass('show');
                        $('.p2-zhz').css('visibility','visible');
                        $('.p2-zhz-2').removeClass('show');
                        $('.p2-zhz-zr').hide();
                        $('.p2-zhz-3').removeClass('show');
                        createBz();
                        var tim2 = setTimeout(function(){
                            $('.p2-bz').removeClass('show');
                        },1500);
                    },2000);

                    //调用召唤接口
                    getC.drawCard();
                    $('#p2-zr-on').removeClass('drag');
                    down=null;
                    // log('something wrong 2');
                }
            }
        }

        //鼠标松开
        function mouseU(e, opts, corner){
            var wW = $(window).width(),
                wH = $(window).height(),
                tOffsetTop = $('.zr-target').offset().top,
                tOffsetLeft = $('.zr-target').offset().left,
                tgH = $('.zr-target').height(),
                tgW = $('.zr-target').width(),
                tmpY = $('.zr-target').offset().top - wH/2,
                tmpX = wW/2 - $('.zr-target').offset().left;
            // e.preventDefault();
            e=e.changedTouches? e.changedTouches[0]:e;
            
            $('#p2-zr-on').removeClass('drag');
            down=null;
        }

        //绑定召唤逻辑事件
        document.getElementById("p2-zr-on").addEventListener(mouseEvents.down,mouseD,false);
        document.addEventListener(mouseEvents.move,mouseM,false);
        document.addEventListener(mouseEvents.up,mouseU,false);
        document.addEventListener(mouseEvents.over,function(e, opts, corner){},false);

    }

    //重抽时 重置抽奖逻辑状态
    function reinit(){
        // document.getElementById("p2-zr-on").removeEventListener(mouseEvents.down,mouseD);
        // document.removeEventListener(mouseEvents.move,mouseM);
        // document.removeEventListener(mouseEvents.up,mouseU);
        ramPlace();
        zhirenXY.X = parseFloat($('.p2-zr-start').css('left'));
        zhirenXY.Y = parseFloat($('.p2-zr-start').css('top'));

        $('.p2-zr-on').css({'display':'none','top':zhirenXY.Y,'left':zhirenXY.X});
        $('.p2-zr-start').show();
        $('.call-btn').removeClass('show');
        $('.p2-zhz-3').removeClass('show');
        $('.p2-zhz-2').removeClass('show');
        $('.p2-bz').removeClass('show');
        $('.p2-zhz-zr').hide();
        $('.p2-zhz').css('visibility','visible');
        if(isAppInside||isIos){
            var st = setTimeout(function(){
                if($('.musicbtn').hasClass('active')){
                    $('#au3')[0].play();
                }
            },400);
        }
        // document.getElementById("p2-zr-on").addEventListener(mouseEvents.down,mouseD,false);
        // document.addEventListener(mouseEvents.move,mouseM,false);
        // document.addEventListener(mouseEvents.up,mouseU,false);
    };


    //用swiper结构来搭建页面
    var _mainSwiper = function(){
        
        mySwiper = new Swiper('.main-swiper', {
            //autoplay: 0,//可选选项，自动滑动
            loop : false,
            // speed:300,
            initialSlide:0,
            onlyExternal : true,
            setWrapperSize :true,
            observer:true,
            observeParents:true,
            effect : 'fade',
            fade: {
                crossFade: true
            },
            onSlideChangeStart: function(e){
                
            },
            onSlideChangeEnd:function(e){
                        
            }
        });


    };

    //打开错误提示
    function warnText(msg){
        var t = $('.err-text');
        t.html(' ');
        t.html(msg);  
        t.show();  
    }

    //关闭错误提示
    function warnTextHide(){
        var t = $('.err-text');
        t.hide();  
    }

    //登陆成功后，跳到抽奖页面
    function loginSuccess(){
        _common.popClose(1);
        canCall = true;
        mySwiper.slideTo(1);    //跳到抽奖页
        if(isAppInside||isIos){
            var st = setTimeout(function(){
                if($('.musicbtn').hasClass('active')){
                    $('#au3')[0].play();
                }
            },400);
        }
        if(!canvasD){
            canvasD = setCanAni();
        }
        if(!canvasD2){
            canvasD2 = setCanAniBz();
        }
        
        cancelAnimationFrame(start);
        start = requestAnimationFrame(stepFn);
        ramPlace();     //随机位置
        ramAni();       //随机动画
    }

    //重置爆炸帧动画
    function createBz(){
        cancelAnimationFrame(start2);
        frameCache = 0;
        start2 = requestAnimationFrame(stepFn2);
    }

    //召唤成功后执行业务逻辑 跳到中奖信息页
    function drawSuccess(data){
        var _html = '',
            pid = data.card_id,
            chanceNum = data.draw_chance;
        imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
        
        
        _html += '<img src="'+ imgSrc +'" alt="式神">';
        $('.ss-now .role').html(' ').html(_html);
        $('.ss-now .sm-changebtn i').html(chanceNum);
        manyCard = data.draw_chance;
        if(chanceNum==0){
            $('.ss-now .sm-changebtn').removeClass('no-chance');
            $('.ss-now .sm-changebtn').addClass('no-chance');
            $('.show-result').show();
        }else{
            $('.show-result').hide();
        }
        if(isfirstsave){
            $('#lxd').html(ssData[pid]);
            $('.ss-now .confirm-yes i').html(ssData[pid]);
            $('.ss-now .confirm-yes').removeClass('firstsave');
            $('.ss-now .confirm-yes').addClass('firstsave');
            lastSaveNum = data.card_id;
            // isfirstsave = false;
        }
    }

    //判断登陆后，用户处于哪一种状态
    function checkLoginDrawStatus(data){
        // if(data.userinfo['last_card_id']==data.userinfo['saved_id']&&data.userinfo['saved_id']!=null){
        //如果用户已经确认式神
        if(data.userinfo['saved_id']!=null){
            $('.ss-already,.ss-now').removeClass('show');
            _common.popClose(1);
            $('.ss-already .confirm-yes').hide();
            $('.ss-already .confirm-yes').addClass('already');
            $('.p3-confirm-final').show();
            $('.p3-btn-wrap .share-btn').show();
            $('.player-info').addClass('yes');
            mySwiper.slideTo(2);
            var _html = '',
                pid = data.userinfo['saved_id'],
                chanceNum = data.userinfo['draw_chance'];
            imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
            _html += '<img src="'+ imgSrc +'" alt="式神">';
            $('.ss-already .role').html(' ').html(_html);
            $('.ss-already').addClass('show');
            // $('.ss-already .sm-changebtn i').html(0);
            // $('.ss-already .sm-changebtn').hide();
            //下面二次方案
            $('.ss-already .sm-changebtn i').html(data.userinfo['draw_chance']);
            if(chanceNum==0){
                $('.ss-already .sm-changebtn').removeClass('no-chance');
                $('.ss-already .sm-changebtn').addClass('no-chance');
            }

            $('#yyzh').html(data.userinfo['mobile']);
            $('#yyqf').html(serverDefault[data.userinfo['hostnum']]);
            // $('#rjsj').html(data.userinfo['op_time']);
            $('#xd').html(ssData[pid]);
            $('#lyyzh').html(data.userinfo['mobile']);
            $('#lyyqf').html(serverDefault[data.userinfo['hostnum']]);
            $('#lxd').html(ssData[pid]);
            //二次方案 修改逻辑之后增加下面代码
            $('.ss-now .confirm-yes').addClass('tihuan');
            $('.ss-now .confirm-yes i').html(ssData[pid]);
            lastSaveNum = data.userinfo['saved_id'];
        }

        //如果用户第一次进入游戏
        else if(data.userinfo['last_card_id']==data.userinfo['saved_id']&&data.userinfo['saved_id']==null){
            // alert('活动已结束，欢迎下次再来！');  //活动结束后才添加的代码
            // _common.popClose(1);    //活动结束后才添加的代码
            // return;  //活动结束后才添加的代码
            loginSuccess();
            //二次方案 修改逻辑之后增加下面代码
            // $('.ss-now .confirm-yes').removeClass('firstsave');
            // $('.ss-now .confirm-yes').addClass('firstsave');
            isfirstsave = true;
        }

        //如果用户抽了一次两次而没有保存式神就退出页面，再次进入页面时
        else if(data.userinfo['last_card_id']!=data.userinfo['saved_id'] && data.userinfo['saved_id']==null){
            // alert('活动已结束，欢迎下次再来！'); //活动结束后才添加的代码
            // _common.popClose(1); //活动结束后才添加的代码
            // return; //活动结束后才添加的代码
            $('.ss-already,.ss-now').removeClass('show');
            _common.popClose(1);
            mySwiper.slideTo(2);
            var _html = '',
                pid = data.userinfo['last_card_id'],
                chanceNum = data.userinfo['draw_chance'];
            imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
            _html += '<img src="'+ imgSrc +'" alt="式神">';
            $('.ss-already .role').html(' ').html(_html);
            $('.ss-already').addClass('show');
            $('.ss-already .sm-changebtn i').html(data.userinfo['draw_chance']);
            if(chanceNum==0){
                $('.ss-already .sm-changebtn').hide();
                $('.ss-already .sm-changebtn').removeClass('no-chance');
                $('.ss-already .sm-changebtn').addClass('no-chance');
            }
            $('#yyzh').html(data.userinfo['mobile']);
            $('#yyqf').html(serverDefault[data.userinfo['hostnum']]);
            // $('#rjsj').html(data.userinfo['op_time']);
            $('#xd').html(ssData[pid]);
        }
    }

    //判断登陆状态
    function switchLoginType(type,data){
        // 1已经登陆(然后判断是否选择服务器)  2未登录
        if(type==1){
            if(data.userinfo['hostnum']){
                checkLoginDrawStatus(data);
                $('#lyyqf').html(serverDefault[data.userinfo['hostnum']]);
                $('#lyyzh').html(serverDefault[data.userinfo['mobile']]);
            }else{
                // log('select server');
                // alert('活动已结束，欢迎下次再来！'); //活动结束后才添加的代码 
                _common.popClose();
                // return; //活动结束后才添加的代码
                var st = setTimeout(function(){
                    _common.popWin('server-wrap');
                },250);
                
            }
        }else if(type==2){
            _common.popWin('login-wrap');
        }else{
            log('something error');
        }
    }

    //确认式神
    function confirmSs(data){
        var getC = _ajxFn();
        getC.lastConfirm(data['userinfo']['last_card_id']);
    }

    //接口调用函数集
    function _ajxFn(){
        
        //判断登陆
        var checkLogin = function(type){
            var urlstr = 'query_userinfo';
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                success : function(data){
                    if(data.status!=true){
                        log(data.msg);
                    }
                    if(type){
                        if(type == 1){
                            if(data.status===true){
                                switchLoginType(1,data);//login ok
                                lastSaveNum = data['userinfo']['saved_id'];
                            }else{
                                switchLoginType(2,data);//login not ok
                            }
                        }
                        if(type == 2){
                            // log(data);
                            confirmSs(data);
                            $('#lyyzh').html(data.userinfo['mobile']);
                            $('#lyyqf').html(serverDefault[data.userinfo['hostnum']]);
                            $('#yyzh').html(data.userinfo['mobile']);
                            $('#yyqf').html(serverDefault[data.userinfo['hostnum']]);
                        }
                    }
                },
                error:function(){
                    alert('网络异常请稍后再试');
                }
            });
        };

        //图片验证码
        var imgCode = function(){
            var urlstr = 'get_img_auth';
            $('#imgcode-btn img').attr('src',hosturl + urlstr+'?' +  Math.random());
        };

        //手机验证码
        var getPhoneCode = function(mobile,imgA){
            var urlstr = 'get_authcode',
                $ds = $('.ds-warn'),
                $senbtn = $('#phonecode-btn');
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                data:{
                    mobile : mobile,
                    img_authcode : imgA
                },
                success : function(data){
                    
                    if(data.status==true){
                        // alert('发送成功');
                        
                        // $('#imgcode-btn').trigger('click');
                        var offnum = 60;
                        t = setInterval(function(){
                            if(offnum == 1){  
                                $ds.hide().html('60s后可再发送');
                            }else{
                                offnum--;
                                $ds.show().html(offnum+'s后可再发送');
                            }
                        },1000);
                        t2 = setTimeout(function(){
                            $senbtn.removeClass('off');
                            clearInterval(t);
                        },61100);
                    }
                    else if(data.status == 501){
                        alert('图片验证码已过期');
                        $senbtn.removeClass('off');
                        $('#imgcode-btn').trigger('click');
                    }
                    else if(data.status == 502){
                        alert('图片验证码错误');
                        $senbtn.removeClass('off');
                        $('#imgcode-btn').trigger('click');
                    }
                    else{
                        alert(data.msg);
                        $senbtn.removeClass('off');
                        $('#imgcode-btn').trigger('click');
                    }
                },
                error:function(){
                    alert('网络异常请稍后再试');
                }
            });
        };
        
        //确认登陆
        var regLogin = function(mobile,phoneCode){
            var urlstr = 'mobile_login';
            
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                data:{
                    mobile : mobile,
                    authcode : phoneCode
                },
                success : function(data){
                    $('#reg-btn').removeClass('off');
                    if(data.status!=true){
                        alert(data.msg);
                    }else{
                        switchLoginType(1,data);
                        $('#lyyzh').html(mobile);
                        $('#yyzh').html(mobile);
                    }
                },
                error:function(){
                    alert('网络异常请稍后再试');
                }
            });
        };

        //选择服务器
        var selectServer = function(hostnum) {
            var urlstr = 'bind_hostnum';
            
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                data:{
                    hostnum : hostnum
                },
                success : function(data){
                    if(data.status!=true){
                        log(data.msg);
                    }else{
                        loginSuccess();
                        //二次方案
                        // $('.ss-now .confirm-yes').removeClass('firstsave');
                        // $('.ss-now .confirm-yes').addClass('firstsave');
                        isfirstsave = true;
                        $('#lyyqf').html(serverDefault[hostnum]);
                        $('#yyqf').html(serverDefault[hostnum]);
                    }
                },
                error:function(){
                    alert('网络异常请稍后再试');
                }
            });
        };

        //抽奖
        var drawCard = function(){

            var urlstr = 'draw';
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                success : function(data){
                    if(data.status!=true){
                        alert(data.msg);
                    }else{
                        cTimer = setTimeout(function(){
                            drawSuccess(data);
                            $('.ss-now,.ss-already').removeClass('show');
                            $('.ss-now').addClass('show');
                            $('.p2-bz').removeClass('show');
                            mySwiper.slideTo(2);
                            cancelAnimationFrame(start2);
                            cancelAnimationFrame(start);
                            clearTimeout(cTimer);
                            cTimer = null;
                        },3500);
                    }
                },
                error:function(){
                    alert('网络异常请稍后再试');
                }
            });
        };

        //保存式神
        var lastConfirm = function(card_id){
            var urlstr = 'save_card';
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                data : {
                    card_id : card_id
                },
                success : function(data){
                    if(data.status!=true){
                        alert(data.msg);
                    }else{
                        $('#lxd').html(ssData[card_id]);
                        lastSaveNum = card_id;

                        _common.popClose(); //替换二次确认时关闭弹层

                        $('.ss-already,.ss-now').removeClass('show');
                        $('.ss-already .confirm-yes').hide();
                        $('.ss-already .confirm-yes').addClass('already');
                        $('.p3-confirm-final').show();
                        $('.p3-btn-wrap .share-btn').show();
                        $('.player-info').addClass('yes');
                        mySwiper.slideTo(2);
                        var _html = '',
                            pid = lastSaveNum,
                            chanceNum = manyCard;
                        imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
                        _html += '<img src="'+ imgSrc +'" alt="式神">';
                        $('.ss-already .role').html(' ').html(_html);
                        $('.ss-already').addClass('show');
                        // $('.ss-already .sm-changebtn i').html(0);
                        // $('.ss-already .sm-changebtn').hide();
                        //下面二次方案
                        $('.ss-already .sm-changebtn i').html(chanceNum);
                        if(chanceNum==0){
                            $('.ss-already .sm-changebtn').removeClass('no-chance');
                            $('.ss-already .sm-changebtn').addClass('no-chance');
                        }

                        $('#xd').html(ssData[pid]);
                        //二次方案 修改逻辑之后增加下面代码
                        $('.ss-now .confirm-yes').addClass('tihuan');
                        $('.ss-now .confirm-yes i').html(ssData[pid]);
                    }
                },
                error:function(){
                    alert('网络异常请稍后再试');
                }
            });
        };

        //分享+1次
        var shareAddCount = function(mobile,phoneCode){
            var urlstr = 'share';
            
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                success : function(data){
                    var sto1 = setTimeout(function(){
                        $('.sm-changebtn i').html(data.draw_chance);
                        $('.sm-changebtn').removeClass('no-chance');
                        if(data.draw_chance==0){
                            $('.sm-changebtn').addClass('no-chance');
                        }
                    },350);
                },
                error:function(){
                    // alert('网络异常请稍后再试');
                    log('网络异常请稍后再试');
                }
            });
        };

        //查询预约人数
        var getYyCount = function(){
            var urlstr = 'query_apntnum';
            
            $.ajax({
                url : hosturl + urlstr,
                type : "get",
                dataType : "jsonp",
                success : function(data){
                    // log(data);
                    if(data.status == true){
                    	initYySuccess(data);
                    }
                    else{
                    	log('网络错误');
                    }
                },
                error:function(){
                    // alert('网络异常请稍后再试');
                    log('网络异常请稍后再试');
                }
            });
        };

        return{
            imgCode : imgCode,
            getPhoneCode : getPhoneCode,
            regLogin : regLogin,
            checkLogin : checkLogin,
            selectServer : selectServer,
            drawCard : drawCard,
            lastConfirm : lastConfirm,
            shareAddCount : shareAddCount,
            getYyCount : getYyCount
        }
    };
    
    //初始化预约人数
    var initYy = function(){
    	var getC = _ajxFn();
        getC.getYyCount();
    }

    //获取预约人数成功后执行函数
    function initYySuccess(lastData){
    	$.ajax({
            url : hosturl2,
            type : "get",
            dataType : "jsonp",
            success : function(data){
                // log(data);
                if(data.status == true){
                	var newData = lastData.usernumber + data.usernumber;
                	var yy = $('.yy-ent'),
			    		yyn = $('.yy-now');
			    	yy.find('i').html(newData);
			    	yyn.html(newData);
			    	if(newData>=100000){
			    		$('.reicon.r1').addClass('cur');
			    	}
			    	if(newData>=300000){
			    		$('.reicon.r2').addClass('cur');
			    		$('.jjt-wrap i').css('width','30%');
			    	}
			    	if(newData>=500000){
			    		$('.reicon.r3').addClass('cur');
			    		$('.jjt-wrap i').css('width','50%');
			    	}
			    	if(newData>=800000){
			    		$('.reicon.r4').addClass('cur');
			    		$('.jjt-wrap i').css('width','70%');
			    	}
			    	if(newData>=1000000){
			    		$('.reicon.r5').addClass('cur');
			    		$('.jjt-wrap i').css('width','100%');
			    	}
                }
                else{
                	log('网络错误');
                }
            },
            error:function(){
                // alert('网络异常请稍后再试');
                log('网络异常请稍后再试');
            }
        });
    }

    //页面事件绑定(按钮点击事件等)
    var _bindEvent = function(){
        $('.p1-go').on('click',function(){
            // mySwiper.slideTo(0, 1000, false);
            //切换到第一个slide，速度为1秒,设置为false时不会触发onSlideChange回调函数。
            var getC = _ajxFn();
            getC.checkLogin(1);
            // _common.popWin('login-wrap');
            // return;
            // mySwiper.slideTo(1);
            // ramPlace();
            // ramAni();
        });
        // $('.call-btn').on('click',function(){
        //     var _this = $(this);
        //     if(_this.hasClass('show')){
        //         mySwiper.slideTo(2);
        //     }
        // });

        $('.yy-ent').on('click',function(){
        	_common.popWin('yuyue-wrap');
        });

        $('.reicon').on('click',function(){
        	var _this = $(this);
        	if(_this.hasClass('show-pop')){
        		return;
        	}
        	$('.reicon').removeClass('show-pop');
        	_this.addClass('show-pop');
        });

        $('.confirm-yes').on('click',function(){
            var _this = $(this);
            if(_this.hasClass('already')){
                // mySwiper.slideTo(2);
                // var stl = setTimeout(function(){
                //     $('.p4').removeClass('ani');
                //     var stl2 = setTimeout(function(){
                //         $('.p4').addClass('ani2');
                //         if(isAppInside||isIos){
                //             $('#au2')[0].play();
                //         }   
                //         $('.last-info').addClass('show');
                //         clearTimeout(stl2);
                //     },50);
                //     clearTimeout(stl);
                // },2000);
                $('.ss-already,.ss-now').removeClass('show');
                $('.ss-already .confirm-yes').hide();
                $('.ss-already .confirm-yes').addClass('already');
                $('.p3-confirm-final').show();
                $('.p3-btn-wrap .share-btn').show();
                $('.player-info').addClass('yes');
                mySwiper.slideTo(2);
                var _html = '',
                pid = lastSaveNum,
                chanceNum = manyCard;
                imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
                _html += '<img src="'+ imgSrc +'" alt="式神">';
                $('.ss-already .role').html(' ').html(_html);
                $('.ss-already').addClass('show');
                // $('.ss-already .sm-changebtn i').html(0);
                // $('.ss-already .sm-changebtn').hide();
                //下面二次方案
                $('.ss-already .sm-changebtn i').html(chanceNum);
                if(chanceNum==0){
                    $('.ss-already .sm-changebtn').removeClass('no-chance');
                    $('.ss-already .sm-changebtn').addClass('no-chance');
                }

                $('#xd').html(ssData[pid]);
                //二次方案 修改逻辑之后增加下面代码
                $('.ss-now .confirm-yes').addClass('tihuan');
                $('.ss-now .confirm-yes i').html(ssData[pid]);

                return;
            }
            if(_this.hasClass('firstsave')){
                // mySwiper.slideTo(2);
                // var stl = setTimeout(function(){
                //     $('.p4').removeClass('ani');
                //     var stl2 = setTimeout(function(){
                //         $('.p4').addClass('ani2');
                //         if(isAppInside||isIos){
                //             $('#au2')[0].play();
                //         }   
                //         $('.last-info').addClass('show');
                //         clearTimeout(stl2);
                //     },50);
                //     clearTimeout(stl);
                // },2000);
                $('.ss-already,.ss-now').removeClass('show');
                $('.ss-already .confirm-yes').hide();
                $('.ss-already .confirm-yes').addClass('already');
                $('.p3-confirm-final').show();
                $('.p3-btn-wrap .share-btn').show();
                $('.player-info').addClass('yes');
                mySwiper.slideTo(2);
                var _html = '',
                pid = lastSaveNum,
                chanceNum = manyCard;
                imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
                _html += '<img src="'+ imgSrc +'" alt="式神">';
                $('.ss-already .role').html(' ').html(_html);
                $('.ss-already').addClass('show');
                // $('.ss-already .sm-changebtn i').html(0);
                // $('.ss-already .sm-changebtn').hide();
                //下面二次方案
                $('.ss-already .sm-changebtn i').html(chanceNum);
                if(chanceNum==0){
                    $('.ss-already .sm-changebtn').removeClass('no-chance');
                    $('.ss-already .sm-changebtn').addClass('no-chance');
                }

                $('#xd').html(ssData[pid]);
                //二次方案 修改逻辑之后增加下面代码
                $('.ss-now .confirm-yes').addClass('tihuan');
                $('.ss-now .confirm-yes i').html(ssData[pid]);

                return;
            }

            _common.popWin('istihuan-wrap');

            // var getC = _ajxFn(); //增加二次替换确认之前保留
            // // getC.lastConfirm();
            // getC.checkLogin(2); //增加二次替换确认之前保留
            // mySwiper.slideTo(2);
            // var stl = setTimeout(function(){
            //     $('.p4').removeClass('ani');
            //     var stl2 = setTimeout(function(){
            //         $('.p4').addClass('ani2');
            //         if(isAppInside||isIos){
            //             $('#au2')[0].play();
            //         }
            //         $('.last-info').addClass('show');
            //         clearTimeout(stl2);
            //     },50);
            //     clearTimeout(stl);
            // },2000);
            
        });
        $('.sm-changebtn').on('click',function(){
            var _this =$(this);
            if(_this.hasClass('no-chance')){
                alert('今日抽奖次数已用完，请明日再来');
                return ;
            }
            //下面3行是二次方案
            isfirstsave = false;
            $('.ss-now .confirm-yes').removeClass('firstsave');
            $('.ss-now .confirm-yes').addClass('tihuan');

            reinit();
            ramAni();
            canCall = true;
            mySwiper.slideTo(1);
            if(!canvasD){
                canvasD = setCanAni();
            }
            if(!canvasD2){
                canvasD2 = setCanAniBz();
            }
            cancelAnimationFrame(start);
            start = requestAnimationFrame(stepFn);
        });

        $('.share-btn').on('click',function(){
            if(isAppInside){
                _common.popWin('share-wrap');
            }else{
                MobileShare.showShare();
            }
            var getC = _ajxFn();
            getC.shareAddCount();
        });

        $('.p1-gz').on('click',function(){
            _common.popWin('guize');
            
        });

        $('.pop-close').on('click',function(){
            _common.popClose();
            
        });

        $('.istihuan-no').on('click',function(){
            _common.popClose();
        });

        $('.istihuan-yes').on('click',function(){
            var getC = _ajxFn(); 
            getC.checkLogin(2); 
        });
        

        $('.pop').on('click',function(e){
            var t = e.target,
                _this = $(this);
            if(t.className === 'pop popup'){
                _common.popClose(_this.attr('id'));
            }
            //隐藏奖励弹窗，不用这种写法似乎有其他bug
            if( t.className != 'reicon-pop'&&
            	t.className != 'js-p'&&
            	t.className != 'top-tit'&&
            	t.className != 'sub-tit'&&
            	t.className != 'reicon r1 show-pop'&&
            	t.className != 'reicon r2 show-pop'&&
            	t.className != 'reicon r3 show-pop'&&
            	t.className != 'reicon r4 show-pop'&&
            	t.className != 'reicon r5 show-pop'){
            	$('.reicon').removeClass('show-pop');
            }
        });

        $('.driver').on('touchstart',function(e){
            e.preventDefault();
            $('.p2-zr-start').hide();
            $('.p2-zr-on').show();
            if(isFirstMove){
                isFirstMove =false;
                moC();
            }
            $('.p2-zr-on').trigger('touchstart');
        });
        
        var _switchSev = function(){
            $('.ser-item').on('click',function(){
                var _this = $(this);
                if(_this.hasClass('cur')){
                    return;
                }
                _this.addClass('cur').siblings().removeClass('cur');
            });
        }();

        $('#imgcode-btn').on('click',function(){
            var getC = _ajxFn();
            getC.imgCode();
        });

        $('#phonecode-btn').on('click',function(){
            var _this =$(this);
            if(_this.hasClass('off')){
                return;
            }
            _this.addClass('off');
            var $phone = $("#phone-num"),
                pnum = $phone.val(),
                $imgcode = $("#img-code"),
                imgcode = $imgcode.val(),
                $phonecode = $("#phone-code"),
                phonecode = $phonecode.val();
            var getC = _ajxFn();
            if(!_common.reg._is_phone(pnum)){
                alert('请输入正确手机号');
                _this.removeClass('off');
                return;
            }
            if(!_common.reg._is_imgcode(imgcode)){
                alert('请输入正确图片验证码');
                _this.removeClass('off');
                return;
            }
            
            getC.getPhoneCode(pnum,imgcode);
        });

        $('#reg-btn').on('click',function(){
            var _this = $(this);
            if(_this.hasClass('off')){
                return;
            }
            _this.addClass('off');
            var $phone = $("#phone-num"),
                pnum = $phone.val(),
                $imgcode = $("#img-code"),
                imgcode = $imgcode.val(),
                $phonecode = $("#phone-code"),
                phonecode = $phonecode.val();
            var getC = _ajxFn();
            if(!_common.reg._is_phone(pnum)){
                alert('请输入正确手机号');
                _this.removeClass('off');
                return;
            }
            // if(!_common.reg._is_imgcode(imgcode)){
            //     alert('请输入正确图片验证码');
            //     _this.removeClass('off');
            //     return;
            // }
            if(!_common.reg._is_phonecode(phonecode)){
                alert('请输入正确手机验证码');
                _this.removeClass('off');
                return;
            }
            getC.regLogin(pnum,phonecode);
            
            // if(_common.reg._is_phone(pnum)&&_common.reg._is_imgcode(imgcode)&&_common.reg._is_phonecode(phonecode)){
            //     warnTextHide();
            // }
        });

        $('.ser-ok').on('click',function(){
            var getC = _ajxFn();
            var serId = parseInt($('.ser-item.cur').attr('set-val'));
            getC.selectServer(serId);
        });

        $('.pre-def').on('touchstart',function(e){
            e.preventDefault();
            return false;
        });

        $('.dlzy').on('click',function(){
            _common.popClose();
            var st = setTimeout(function(){
                _common.popWin('wxts');
            },250);
        });

        $('.l-close').on('click',function(){
            $('.last-info').removeClass('show');
        });

        $('.show-result').on('click',function(){
            $('.ss-already,.ss-now').removeClass('show');
            $('.ss-already .confirm-yes').hide();
            $('.ss-already .confirm-yes').addClass('already');
            $('.p3-confirm-final').show();
            $('.p3-btn-wrap .share-btn').show();
            $('.player-info').addClass('yes');
            mySwiper.slideTo(2);
            var _html = '',
                pid = lastSaveNum,
                chanceNum = manyCard;
            imgSrc = __CDNPATH + '/data/pic/'+pid+'.png?';
            _html += '<img src="'+ imgSrc +'" alt="式神">';
            $('.ss-already .role').html(' ').html(_html);
            $('.ss-already').addClass('show');
            // $('.ss-already .sm-changebtn i').html(0);
            // $('.ss-already .sm-changebtn').hide();
            //下面二次方案
            $('.ss-already .sm-changebtn i').html(chanceNum);
            if(chanceNum==0){
                $('.ss-already .sm-changebtn').removeClass('no-chance');
                $('.ss-already .sm-changebtn').addClass('no-chance');
            }

            $('#xd').html(ssData[pid]);
            //二次方案 修改逻辑之后增加下面代码
            $('.ss-now .confirm-yes').addClass('tihuan');
            $('.ss-now .confirm-yes i').html(ssData[pid]);
        });

        //音乐控制
        $('.musicbtn').on('click',function(){
            var _t = $(this);
            if(_t.hasClass('active')){
                _t.removeClass('active');
                $('#au1')[0].pause();
            }else{
                _t.addClass('active');
                $('#au1')[0].play();
            }
        });

    }


    //预加载调用
    Loader.show({
        iFileData: img_list,
        bgColor: '#000',//loading背景色值，默认#000
        mainWrap: '#main',//主题内容DOM，默认id值是Jmain
        defaultAnimation: false,//布尔值，默认值true。是否显示默认的loading动画
        customAnimation: function(curPer){//加载进度回调函数，取值0~1
            // console.log(curPer);
            $('.text-line,.jd-line').css('width',curPer*100+'%');
        },
        completeCallback: function(){//完成预加载回调函数
            // var st2 = setTimeout(function(){
            //     $('.load-wrap').css('opacity','0');
            // },2000);
            // var st = setTimeout(function(){
            //     $('.load-wrap').hide().css('visibility','hidden');
            //     $('.load-wrap').remove();
            // },2300);
            // var st2 = setTimeout(function(){
            //     $('#main').removeClass('start-ani');
            // },3000);
            // //正式发布换上2000和2300,3000
            // _init();
            var st2 = setTimeout(function(){
	            $('.load-btn').addClass('loaded');
                $('.load-wrap').on('touchstart',function(){
                    $('#au1')[0].play();//音效只在双平台微信，以及safari下执行，背景乐全平台执行
                    if(isAppInside||isIos){ //修复ios下音效不对应bug 
                        $('#au2')[0].play();
                        $('#au3')[0].play();
                        $('#au4')[0].play();
                        $('#au5')[0].play();
                        $('#au2')[0].pause();
                        $('#au3')[0].pause();
                        $('#au4')[0].pause();
                        $('#au5')[0].pause();
                    }

                    $('.load-wrap').css('opacity','0');
                    var st = setTimeout(function(){
                        $('.load-wrap').hide().css('visibility','hidden');
                        $('.load-wrap').remove();
                        $('.p1-chuo').addClass('show');
                    },300);
                    if(isAppInside||isIos){
                        var st3 = setTimeout(function(){
                            if($('.musicbtn').hasClass('active')){
                                $('#au2')[0].play();
                            }
                        },600);
                    }
                    var st2 = setTimeout(function(){
                        $('#main').removeClass('start-ani');
                    },1000);
                });
            },2000); //loading加载完之后，给两秒用于缓冲页面
            _init();
        }
    });

    function _init(){
        _mainSwiper();
        _bindEvent();
        initYy();
        // setLogin();
        cachefiresImg();

    };
    
});

function log(t){
    console.log(t);
}